package com.example.service.impl;

import com.example.dto.StudentDetailDTO;
import com.example.mapper.GoodsMapper;
import com.example.mapper.StudentMapper;
import com.example.pojo.Goods;
import com.example.pojo.PageBean;
import com.example.pojo.Student;
import com.example.service.StudentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public PageBean<Student> list(Integer pageNum, Integer pageSize, String name) {
        // 1. 设置分页参数
        PageHelper.startPage(pageNum, pageSize);

        // 2. 执行查询
        List<Student> students = studentMapper.list(name);

        // 3. 获取分页结果
        Page<Student> page = (Page<Student>) students;

        // 4. 封装PageBean
        PageBean<Student> pb = new PageBean<>();
        pb.setTotal(page.getTotal());
        pb.setItems(page.getResult());

        return pb;
    }

    @Override
    public Student findById(Integer id) {
        return studentMapper.findById(id);
    }

    @Override
    public StudentDetailDTO getStudentDetail(Integer id) {
        StudentDetailDTO detail = new StudentDetailDTO();

        // 1. 查询学生基本信息
        Student student = studentMapper.findById(id);
        if (student == null) {
            throw new RuntimeException("学生不存在");
        }

        // 处理默认头像
        if (student.getStuPic() == null || student.getStuPic().isEmpty()) {
            student.setStuPic("/assets/default.png");
        }

        // 2. 查询发布的商品
        List<Goods> publishedGoods = studentMapper.findPublishedGoods(id);

        // 3. 查询购买的商品
        List<Goods> purchasedGoods = studentMapper.findPurchasedGoods(id);

        detail.setStudent(student);
        detail.setPublishedGoods(publishedGoods);
        detail.setPurchasedGoods(purchasedGoods);

        return detail;
    }

    @Override
    public void increaseStudentCreditScore(Integer id, int points) {
        Student student = studentMapper.findById(id);
        if (student != null) {
            int newCreditScore = student.getCreditScore() + points;
            if (newCreditScore > 100) {
                newCreditScore = 100;
            }
            studentMapper.updateCreditScore(id, newCreditScore);
        }
    }

    @Override
    public void decreaseStudentCreditScore(Integer id, int points) {
        Student student = studentMapper.findById(id);
        if (student != null) {
            int newCreditScore = student.getCreditScore() - points;
            if (newCreditScore < 0) {
                newCreditScore = 0;
            }
            studentMapper.updateCreditScore(id, newCreditScore);
        }
    }
}